#!/usr/bin/env python
# -*- coding: utf-8 -*-


from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine


class GeekItem(object):  # 创建一个映射类

    def to_item(self):
        res = {}
        res['cityid'] = self.cityid
        res['task'] = self.task
        res['score'] = self.score
        return res

    def __repr__(self):
        return "%d" % (self.urlid)

# 创建到数据库的连接,echo=True表示用logging输出调试结果
metadata = MetaData()
Session = sessionmaker()  # 创建了一个自定义了的 Session类
Session.configure(bind=engine)  # 将创建的数据库连接关联到这个session
geek_item_table = Table(
    'geek_item', metadata,
    Column('id', Integer, primary_key=True),
    Column('cityid', Integer, index=True, nullable=False),
    Column('score', BigInteger, index=True, nullable=False),
    Column('ctime', DateTime, default=datetime.now)
)


def createGeekItemTable():
    metadata.create_all(engine)  # 在数据库中生成表
    mapper(GeekItem, geek_item_table)  # 把表映射到类


createGeekItemTable()


def add_geek_item(pItem):
    try:
        session = Session()
        session.add(pItem)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def update_name(pAppid, pName):
    try:
        session = Session()
        session.query(GeekItem).filter(GeekItem.appid == pAppid).update({GeekItem.name: pName},
                                                                        synchronize_session=False)
        session.commit()  # 提交事务
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


if __name__ == "__main__":
    item3 = GeekItem()
    Column('cityid', Integer, index=True, nullable=False),
    Column('score', BigInteger, index=True, nullable=False),
    item3.cityid = 1
    item3.score = 8
    add_geek_item(item3)
    '''
    pUrlids = [200000715]
    item_dict = get_item_dict( pUrlids )
    print item_dict
    '''
